<script setup lang="tsx">
import { h, onMounted, ref } from 'vue';
import { NButton, NTag } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import type { SmsLog } from '@/service/api';
import { fetchSmsChannelOptions, fetchSmsLogList } from '@/service/api';
import { useAppStore } from '@/store/modules/app';
import { $t } from '@/locales';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import { useAuth } from '@/hooks/business/auth';
import SvgIcon from '@/components/custom/svg-icon.vue';
import SmsLogSearch from './modules/sms-log-search.vue';
import SmsLogDetailModel from './modules/sms-log-detail-model.vue';

const wrapperRef = ref<HTMLElement | null>(null);
const appStore = useAppStore();
const { hasAuth } = useAuth();

const channelList = ref<CommonType.OptionExtra<number>[] | null>([]); // 短信渠道列表

const { columns, data, loading, mobilePagination, getData, getDataByPage, searchParams, resetSearchParams } = useTable({
  apiFn: fetchSmsLogList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    mobile: null,
    channelId: null,
    templateId: null,
    sendStatus: null,
    sendTime: null,
    receiveStatus: null,
    receiveTime: null
  },
  columns: () => [
    {
      key: 'id',
      title: $t('page.base.sms.log.id'),
      align: 'center',
      width: 80
    },
    {
      key: 'createTime',
      title: $t('page.base.sms.log.createTime'),
      align: 'center',
      width: 120
    },
    {
      key: 'mobile',
      title: $t('page.base.sms.log.mobile'),
      align: 'center',
      width: 120,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.userType && row.userId) {
          const dictObj = getDictObj(DICT_TYPE.USER_TYPE, row.userType);
          return (
            <div>
              <div>{row.mobile}</div>
              <div>
                <NTag type={dictObj?.colorType} class="mr-2">
                  {dictObj?.label}
                </NTag>
                {`(${row.userId})`}
              </div>
            </div>
          );
        }
        return row.mobile;
      }
    },
    {
      key: 'templateContent',
      title: $t('page.base.sms.log.templateContent'),
      align: 'center',
      width: 300,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'sendStatus',
      title: $t('page.base.sms.log.sendStatus'),
      align: 'center',
      width: 180,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.sendStatus === null) {
          return '~';
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_SMS_SEND_STATUS, row.sendStatus);

        return (
          <div>
            <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>
            <div>{row.sendTime}</div>
          </div>
        );
      }
    },
    {
      key: 'receiveStatus',
      title: $t('page.base.sms.log.receiveStatus'),
      align: 'center',
      width: 180,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.receiveStatus === null) {
          return '~';
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_SMS_RECEIVE_STATUS, row.receiveStatus);

        return (
          <div>
            <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>
            <dir>{row.receiveTime}</dir>
          </div>
        );
      }
    },
    {
      key: 'channelId',
      title: $t('page.base.sms.log.channelId'),
      align: 'center',
      width: 180,
      ellipsis: {
        tooltip: true
      },
      render: row => {
        if (row.sendStatus === null) {
          return '~';
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE, row.channelCode);

        return (
          <div>
            {channelList.value?.find(channel => channel.value === row.channelId)?.extra}
            <NTag type={dictObj?.colorType} class="ml-2">
              {dictObj?.label}
            </NTag>
          </div>
        );
      }
    },
    {
      key: 'templateId',
      title: $t('page.base.sms.log.templateId'),
      align: 'center',
      width: 80
    },
    {
      key: 'templateType',
      title: $t('page.base.sms.log.templateType'),
      align: 'center',
      width: 80,
      render: row => {
        if (row.templateType === null) {
          return '~';
        }
        const dictObj = getDictObj(DICT_TYPE.SYSTEM_SMS_TEMPLATE_TYPE, row.templateType);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 100,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:sms-log:query')}>
            <NButton type="primary" ghost size="small" onClick={() => openDetail(row)}>
              {{
                default: () => $t('common.detail'),
                icon: () => h(SvgIcon, { icon: 'ph:eye' })
              }}
            </NButton>
          </div>
        </div>
      )
    }
  ]
});

const { modelVisible, editingData, handleEdit } = useTableOperate(data, getData);

function openDetail(row: SmsLog) {
  handleEdit(row.id);
}

onMounted(async () => {
  // 加载渠道列表
  const { data: res } = await fetchSmsChannelOptions();
  channelList.value = res;
});
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <SmsLogSearch
      v-if="hasAuth('system:sms-log:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />

    <NCard :title="$t('page.base.sms.log.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation :loading="loading" create-show="false" delete-show="false" @refresh="getData" />
      </template>
      <NDataTable
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="2088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />

      <SmsLogDetailModel v-model:visible="modelVisible" :row-data="editingData" />
    </NCard>
  </div>
</template>

<style scoped></style>
